﻿using HslCommunication.Profinet.Siemens;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Configuration;
using System.Text.RegularExpressions;
using HslCommunication.LogNet;
using System.Diagnostics;
using System.Xml.Linq;


namespace 南京数化易达测长测重
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
            // 设置 NotifyIcon 的双击事件

           
            notifyIcon2.DoubleClick += notifyIcon2_DoubleClick;

            // 窗体的最小化事件
            this.Resize += Form1_Resize;
        }
        private SiemensS7Net siemensChanXian = null;
        private SiemensS7Net siemensCeChang= null;
        private OperateResult PLCconnectChanXian = null;
        private OperateResult PLCconnectCeChang = null;
        bool ComClose = false;
        bool run = true;
        bool Listening = false;
        private string endflag= "\r\n";
        private TcpClient tcpclient = null;
        private ILogNet logNetYX = new LogNetDateTime(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Logs\\LogYXs", GenerateMode.ByEveryHour);
        
        private void Form1_Load(object sender, EventArgs e)
        {
            logNetYX.WriteInfo("软件开启", "软件开启程序执行");
            
            //称重串口
            ChengZhong();

            //扫码串口
            SaoMa();

            //产线PLC
            PLCChanXian();

            //测长PLC
            PLCCeChang();

            //喷码连接
            DaMa();
          
            Task task = new Task(() =>
            {
                while (run)
                {
                    try
                    {
                        #region 运行流程
                        //读取养号
                        //读取长度、直径、重量、写入PLC
                        Thread.Sleep(1000);

                        //PLC触发上传信号、上传数据到数据库；------长度、直径、重量、mode
                        if (PLCconnectCeChang.IsSuccess)
                        {
                            string AAA = siemensCeChang.ReadString("DB11.34.0").Content.Trim();
                            logNetYX.WriteInfo("连接测长PLC", "读取样号值：" + AAA);
                            if (AAA.Length > 5)
                            {
                                m2_procedureprogres_vol m2_Procedureprogres_VolA = m2_Procedureprogres_VolServer.GetSingle(110, 210, AAA);
                                //读取数据库允许离开，并下发产线
                                if (m2_Procedureprogres_VolA != null)
                                {
                                    if (m2_Procedureprogres_VolA.Mode == 110)  //合格或不合格
                                    {
                                        logNetYX.WriteInfo("连接数据库", "读取mode值为" + "110");
                                        if (PLCconnectChanXian.IsSuccess)
                                        {
                                            if ((m2_Procedureprogres_VolA.reason != null) && (m2_Procedureprogres_VolA.CodeBatch != null))
                                            {
                                                DaBiaoSend(m2_Procedureprogres_VolA.reason, m2_Procedureprogres_VolA.CodeBatch.Trim());//喷码信息
                                                if (siemensChanXian.Write("DB100.2.0", 86).IsSuccess)
                                                {
                                                    logNetYX.WriteInfo("连接产线PLC", "写入DB1002.0为86成功");
                                                    m2_Procedureprogres_VolServer.UpdateMode(120, m2_Procedureprogres_VolA.CodeBatch);
                                                    logNetYX.WriteInfo("连接数据库", "更新对应码值" + m2_Procedureprogres_VolA.CodeBatch + "mode状态为" + "120");
                                                }
                                                else
                                                {
                                                    logNetYX.WriteInfo("连接产线PLC", "写入DB100.2.0为86失败");
                                                    m2_Procedureprogres_VolServer.UpdateMode(9120, m2_Procedureprogres_VolA.CodeBatch);
                                                    logNetYX.WriteInfo("连接数据库", "更新对应码值" + m2_Procedureprogres_VolA.CodeBatch + "mode状态为" + "9120");
                                                }

                                            }
                                            else
                                            {
                                                logNetYX.WriteInfo("连接数据库", "获取喷印信息时，reason或CodeBatch存在空信息");

                                            }
                                            

                                        }
                                    }
                                    else if (m2_Procedureprogres_VolA.Mode == 210)//合格或不合格
                                    {
                                        logNetYX.WriteInfo("连接数据库", "读取mode值为" + "210");
                                        if (PLCconnectChanXian.IsSuccess)
                                        {
                                            if ((m2_Procedureprogres_VolA.reason != null) && (m2_Procedureprogres_VolA.CodeBatch != null))
                                            {
                                                DaBiaoSend(m2_Procedureprogres_VolA.reason, m2_Procedureprogres_VolA.CodeBatch.Trim());//喷码信息
                                                if (siemensChanXian.Write("DB100.2.0", 86).IsSuccess)
                                                {
                                                    logNetYX.WriteInfo("连接产线PLC", "写入DB100.2.0为86成功");
                                                    m2_Procedureprogres_VolServer.UpdateMode(220, m2_Procedureprogres_VolA.CodeBatch);
                                                    logNetYX.WriteInfo("连接数据库", "更新对应码值" + m2_Procedureprogres_VolA.CodeBatch + "mode状态为" + "220");
                                                }
                                                else
                                                {
                                                    logNetYX.WriteInfo("连接产线PLC", "写入DB100.2.0为86失败");
                                                    m2_Procedureprogres_VolServer.UpdateMode(9220, m2_Procedureprogres_VolA.CodeBatch);
                                                    logNetYX.WriteInfo("连接数据库", "更新对应码值" + m2_Procedureprogres_VolA.CodeBatch + "mode状态为" + "9220");
                                                }

                                            }
                                            else
                                            {
                                                logNetYX.WriteInfo("连接数据库", "获取喷印信息时，reason或CodeBatch存在空信息");

                                            }
                                             

                                        }

                                    }

                                }
                            }

                            //读取PLC称重测长完成信号
                            if (siemensCeChang.ReadBool("DB11.0.2").Content)
                            {
                                logNetYX.WriteInfo("连接测长PLC", "读取DB11.0.2，上传信号为true");

                                siemensCeChang.Write("DB11.0.2", false);  //上传信号
                                logNetYX.WriteInfo("连接测长PLC", "写入DB11.0.2，上传信号为false");
                                m2_procedureprogres_vol m2_Procedureprogres_Vol = new m2_procedureprogres_vol
                                {
                                    CodeBatch = siemensCeChang.ReadString("DB11.34.0").Content,//样号
                                    DiameterAuto = siemensCeChang.ReadFloat("DB11.10.0").Content,//直径
                                    Mode = 100,
                                    WeightAuto = siemensCeChang.ReadFloat("DB11.2.0").Content,//重量
                                    WidthClothAuto = siemensCeChang.ReadFloat("DB11.6.0").Content//长度（幅宽）
                                };
                                logNetYX.WriteInfo("连接数据库", "准备写入样号为：" + m2_Procedureprogres_Vol.CodeBatch.ToString());
                                logNetYX.WriteInfo("连接数据库", "准备写入直径为：" + m2_Procedureprogres_Vol.DiameterAuto.ToString());
                                logNetYX.WriteInfo("连接数据库", "准备写入重量为：" + m2_Procedureprogres_Vol.WeightAuto.ToString());
                                logNetYX.WriteInfo("连接数据库", "准备写入长度（幅宽）为：" + m2_Procedureprogres_Vol.WidthClothAuto.ToString());
                                logNetYX.WriteInfo("连接数据库", "准备写入mode为：" + m2_Procedureprogres_Vol.Mode.ToString());
                                //本地有一个数据库，写入本地，注释否是成功字段，不成功自动传输
                                //是否加一个写入失败
                                int row= m2_Procedureprogres_VolServer.Update(m2_Procedureprogres_Vol); //返回受影响行数
                                if (row > 0)
                                {
                                    logNetYX.WriteInfo("连接数据库", "更新数据成功");
                                }
                                else
                                {
                                    logNetYX.WriteInfo("连接数据库", "更新数据失败");
                                }
                                
                                siemensCeChang.Write("DB11.0.3", true);
                                logNetYX.WriteInfo("连接测长PLC", "写入DB11.0.3，信号为true");
                            }
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        logNetYX.WriteInfo("异常", "异常信息为：" + ex.Message.ToString());
                        throw ex;
                    }
                }


            });
            task.Start();

        }
        void PLCChanXian()
        {
            siemensChanXian = new SiemensS7Net(SiemensPLCS.S1200, "192.168.10.10");
            PLCconnectChanXian = siemensChanXian.ConnectServer();
			if (PLCconnectChanXian.IsSuccess)
            {
                label4.Text = "连接PLC成功!";
                logNetYX.WriteInfo("连接产线PLC", "连接成功");
            }
			else

            {
                label4.Text = "连接PLC失败!";
                logNetYX.WriteInfo("连接产线PLC", "连接失败");
            }

        }
        void PLCCeChang()   //地址需要改变与现场要求相符合
        {
            siemensCeChang = new SiemensS7Net(SiemensPLCS.S1200, "192.168.10.111");
            PLCconnectCeChang = siemensCeChang.ConnectServer();
            if (PLCconnectCeChang.IsSuccess)
            {
                label5.Text = "连接PLC成功!";
                logNetYX.WriteInfo("连接测长PLC", "连接成功");
            }
            else
            {
                label5.Text = "连接PLC失败!";
                logNetYX.WriteInfo("连接测长PLC", "连接失败");
            }

        }

        #region 串口
        private void ChengZhong()
        {
            // 设置串口参数
            string COMchengzong = ConfigurationManager.ConnectionStrings["COMchengzong"].ConnectionString;
            serialPort1.PortName = COMchengzong; // 端口名称
            serialPort1.BaudRate = 9600; // 建议设置为实际需要的波特率（例如 9600）
            serialPort1.Parity = Parity.None; // 校验位
            serialPort1.StopBits = StopBits.One; // 停止位
            serialPort1.DataReceived += CZ_DataReceived; // 数据接收事件
            serialPort1.ReceivedBytesThreshold = 1; // 接收字节阈值

            logNetYX.WriteInfo("称重串口", "串口初始化，端口号为："+ serialPort1.PortName.ToString());
            // 尝试打开串口
            try
            {
                serialPort1.Open();
                label6.Text = "端口"+ serialPort1.PortName.ToString()+ "连接成功";
                logNetYX.WriteInfo("称重串口", "串口初始化，串口成功打开");
                // 这里可以根据需要发送 AT 命令
                // string text = this.ATCommand("AT+CLIP=1\r", "OK");
            }
            catch (Exception ex) // 捕获具体异常
            {
                label6.Text = "端口连接失败: " + ex.Message; // 显示失败信息
                logNetYX.WriteInfo("称重串口", "串口初始化，串口打开失败，异常信息为：" + ex.Message.ToString());
            }

        }
        //private StringBuilder _currentDataBuffer = new StringBuilder();
        private string StartDelimiter = "\u0002*0"; // 假设开始符号
        private string EndDelimiter = "\r\n";   // 假设结束符号

        private volatile bool isClosing = false;
        public void CZ_DataReceived(object sender, SerialDataReceivedEventArgs e)  //实时写入称重值到PLC中
        {

            if (isClosing) return; // 如果正在关闭，直接返回
            // 这里定义一个类级变量以存储接收到的串口内容
            //string receivedData = string.Empty;

            try
            {
                if (serialPort1.IsOpen)
                {
                    Thread.Sleep(200);
                    int length = serialPort1.BytesToRead;
                    string receivestring = serialPort1.ReadExisting();
                    //logNetYX.WriteInfo("称重串口", "接收字节长度:" + length.ToString());
                    //logNetYX.WriteInfo("称重串口", "接收字节信息:" + receivestring);

                    if (length > 17)
                    {
                        logNetYX.WriteInfo("称重串口", "接收字节长度大于17");
                        string receivedChar = receivestring;

                        // 检查开始符号
                        // receivedData += receivedChar; // 累加接收到的数据
                        //logNetYX.WriteInfo("称重串口", "接收串口信息为：" + receivedChar.ToString());
                        //if ((receivedChar.ToString().Contains(StartDelimiter)) && (receivedChar.ToString().Contains(EndDelimiter)))   //其中包含开始字符 和结束字符
                        //{
                        //logNetYX.WriteInfo("称重串口", "接收串口信息其中包含开始字符及结束字符");
                        // 在开始和结束符号之间积累字符

                        var data = GetUniqueConcatenatedString3(receivedChar.ToString());
                        //logNetYX.WriteInfo("称重串口", "处理后串口信息为" + data.ToString());

                        string weight = returnweight(data.ToString());
                        logNetYX.WriteInfo("称重串口", "处理后重量信息为" + weight.ToString());
                        // 更新 UI 控件
                        UpdateLabelWeight(weight);
                        if (PLCconnectCeChang.IsSuccess)
                        {
                            logNetYX.WriteInfo("连接测长PLC", "写入测长PLC重量为：" + weight);// 实时写入称重值

                            siemensCeChang.Write("DB11.2.0", float.Parse(weight));
                        }

                        // 清空接收到的串口内容，准备接收新的数据
                        receivedChar = string.Empty;
                        //}

                    }
                }
               
            }
            catch(Exception ex)
            {
                logNetYX.WriteInfo("称重串口", "串口异常，异常信息为：" + ex.Message.ToString());
            }
            finally
            {
                serialPort1.DiscardInBuffer(); // 丢弃输入缓冲区的所有数据
                logNetYX.WriteInfo("称重串口", "清理串口数据");
                //receivedChar = string.Empty; // 清理接收到的串口内容
                this.Listening = false;
            }

        }

        private void SaoMa()
        {
            string COMsaoma = ConfigurationManager.ConnectionStrings["COMsaoma"].ConnectionString;
            // 设置串口参数
            serialPort2.PortName = COMsaoma; // 端口名称
            serialPort2.BaudRate = 9600; // 建议设置为实际需要的波特率（例如 9600）
            serialPort2.Parity = Parity.None; // 校验位
            serialPort2.StopBits = StopBits.One; // 停止位
            //serialPort2.DataReceived += Sm_DataReceived; // 数据接收事件
            serialPort2.ReceivedBytesThreshold = 1; // 接收字节阈值

            serialPort2.DataReceived += new SerialDataReceivedEventHandler(Sm_DataReceived);//DataReceived 事件委托

            serialPort2.RtsEnable = true;

            logNetYX.WriteInfo("扫码串口", "串口初始化，端口号为：" + serialPort2.PortName.ToString());

            // 尝试打开串口
            try
            {
                serialPort2.Open();
                label13.Text = "端口"+ serialPort2.PortName+"连接成功";
                logNetYX.WriteInfo("扫码串口", "串口初始化，串口成功打开");
                // 这里可以根据需要发送 AT 命令
                // string text = this.ATCommand("AT+CLIP=1\r", "OK");
            }
            catch (Exception ex) // 捕获具体异常
            {
                label13.Text = "端口连接失败: " + ex.Message; // 显示失败信息
                logNetYX.WriteInfo("扫码串口", "串口初始化，串口打开失败，异常信息为：" + ex.Message.ToString());
            }

        }
        public void Sm_DataReceived(object sender, SerialDataReceivedEventArgs e)  //实时写入扫码数值到PLC中
        {
            if (isClosing) return; // 如果正在关闭，直接返回
            if (serialPort2.IsOpen)
            {
                int num2 = serialPort2.BytesToRead;
                logNetYX.WriteInfo("扫码串口", "接收串口信息字节长度为：" + num2.ToString());
                if (num2 > 0)
                {
                    try
                    {
                        string text = serialPort2.ReadExisting();

                        if (text != null)
                        {
                            logNetYX.WriteInfo("扫码串口", "接收串口信息为：" + text.ToString());
                            if (text.Length > 5)
                            {
                                logNetYX.WriteInfo("扫码串口", "接收串口信息字符长度大于5");
                                string ewm = GetUniqueConcatenatedString2(text);//处理提取不同的字符串  并去掉其中\r\n（防止出现多次扫码的情况）
                                logNetYX.WriteInfo("扫码串口", "接收串口处理后信息为:" + ewm.ToString());
                                string ph = ExtractNumbers(ewm);//扫码找到纯数字部分就是对应的批号 码值
                                logNetYX.WriteInfo("扫码串口", "接收串口处理后的批号信息为:" + ph.ToString());

                                //更新UI
                                UpdateLabelsaoma(ph);

                                //实时写入扫码值
                                if (PLCconnectCeChang.IsSuccess)
                                {
                                    // 实时写入样号 批号
                                    siemensCeChang.Write("DB11.34.0", ph);
                                    logNetYX.WriteInfo("连接测长PLC", "写入测长PLC批号为：" + ph.ToString());
                                }
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        logNetYX.WriteInfo("扫码串口", "串口异常，异常信息为：" + ex.Message.ToString());
                    }
                    finally
                    {
                        serialPort2.DiscardInBuffer(); // 丢弃输入缓冲区的所有数据
                        logNetYX.WriteInfo("扫码串口", "清理串口数据");
                        

                    }
                } 
            }

           
        }
        #endregion

        private void PrintFastReport(string no, string orderno, bool isVisible)
		{
			//string sqlstring = string.Concat(new string[]
			//{
			//	"SELECT * From invp_product join invm_product on invp_product.fno=invm_product.fno where invp_product.fno='",
			//	no,
			//	"' and fproduceno='",
			//	orderno,
			//	"' "
			//});
			//DataSet dataSet = new DataSet();
			//SQLHelper.FillDataSet(dataSet, sqlstring, "invr_product");
			//int num = int.Parse(this.textBox13.Text);
			//string fileName = Application.StartupPath + "\\Report\\仓库管理\\成品入库\\入库标签\\产品标签.frx";
			//if (this.comboBox4.Text.Trim() != "")
			//{
			//	fileName = Application.StartupPath + "\\Report\\仓库管理\\成品入库\\入库标签\\" + this.comboBox4.Text.Trim() + ".frx";
			//}
			//dataSet.Tables[0].Columns.Add("ftm", Type.GetType("System.Byte[]"));
			//dataSet.Tables[0].Columns.Add("QRcode", Type.GetType("System.Byte[]"));
			//foreach (object obj in dataSet.Tables["invr_product"].Rows)
			//{
			//	DataRow dataRow = (DataRow)obj;
			//	byte[] array = ITM.gettm(this.tmtype, dataRow["fproduceno"].ToString().Trim());
			//	byte[] array2 = ITM.gettm("二维码", dataRow["fproduceno"].ToString().Trim());
			//	if (array != null)
			//	{
			//		dataRow["ftm"] = array;
			//	}
			//	if (array2 != null)
			//	{
			//		dataRow["QRcode"] = array2;
			//	}
			//}
			//Report report = new Report();
			//report.Load(fileName);
			//report.RegisterData(dataSet);
			//if (isVisible)
			//{
			//	report.Show();
			//}
			//else
			//{
			//	for (int i = 0; i < num; i++)
			//	{
			//		report.PrintSettings.ShowDialog = false;
			//		report.Print();
			//	}
			//}
		}

        #region 打标信息
        private void DaMa()
        {
            try
            {
                 tcpclient = new TcpClient("192.168.10.51", 9100);
                //tcpclient = new TcpClient("127.0.0.1", 502);
                if (tcpclient != null)
                {
                    lbl_COM.Text = "喷码TCP连接成功";
                    logNetYX.WriteInfo("喷码连接", "喷码连接成功");
                }
                else
                {
                    lbl_COM.Text = "喷码TCP连接失败";
                    logNetYX.WriteInfo("喷码连接", "喷码连接失败");
                    MessageBox.Show("TCP建立连接失败", "提示");
                }
            }
            catch (Exception ex)
            {
                logNetYX.WriteInfo("喷码连接异常", ex.Message.ToString());
                throw;
            }
        }
        private void DaBiaoSend(string message1, string message2)
        {
            logNetYX.WriteInfo("连接喷码", "接收喷码信息1为："+ message1.ToString()+ "接收喷码信息2为：" + message2.ToString());
            //读取数据库
            if (this.tcpclient != null)
            {
                //170g-2100-1622KG-AA"

                string message3= message2+ DateTime.Now.ToString("HH:mm"); //批号加上时间 是第二条喷印信息

                TCPSendData("!!" + "v!1" + '"' + message1 + '"' + (char)13 + "!!" + "v!2" + '"' + message3 + '"' + (char)13 + "!!" + "v!1?" + (char)13 + "!!" + "v!2?" + (char)13);//喷码信息1和2

                logNetYX.WriteInfo("连接喷码", "发送喷码信息1为：" + message1.ToString() + "发送喷码信息2为：" + message3.ToString()+"到喷码机");
            }

        }
      
        public void TCPSendData(string data)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(data);
            try
            {
                this.tcpclient.Client.Send(bytes);
            }
            catch (Exception ex)
            {
                MessageBox.Show("发送喷码错误:"+ex.ToString());
                logNetYX.WriteInfo("喷码连接异常", ex.Message.ToString());
            }
        }

        #endregion

        #region 将重量及扫码信息显示到页面上
        // 更新标签的方法
        private void UpdateLabelWeight(string weight)
        {

            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action<string>(UpdateLabelWeight), weight); // 异步调用
            }
            else
            {
                labelWeight.Text = weight;
            }



        }

        private void UpdateLabelsaoma(string saoma)
        {
            // 检查是否在 UI 线程上
            //if (labelsaoma.InvokeRequired)
            //{
            //    // 在 UI 线程上调用 UpdateLabelWeight
            //    labelsaoma.Invoke(new Action<string>(UpdateLabelsaoma), saoma);
            //}
            //else
            //{
            //    // 更新 label 的文本
            //    labelsaoma.Text = saoma;
            //}


            if (this.InvokeRequired)
            {
                this.BeginInvoke(new Action<string>(UpdateLabelsaoma), labelsaoma); // 异步调用
            }
            else
            {
                labelsaoma.Text = saoma;
            }


        }

        #endregion

        #region 处理接收到的串口内容方法
        //处理接收到的串口内容方法
        private string returnweight(string text)
        {

            // 清理字符串，去掉非可见字符
            string cleanedInput = Regex.Replace(text, @"[^\x20-\x7E]", " "); // 替换非可见字符为空格

            // 输出清理后的字符串以进行调试
            //Console.WriteLine("Cleaned Input: " + cleanedInput);

            // 匹配所有数字
            MatchCollection matches = Regex.Matches(cleanedInput, @"\d+");
            foreach (Match match in matches)
            {
                Console.WriteLine("Matched Number: " + match.Value); // 输出所有匹配的数字
            }

            // 如果只想获取第一个匹配的数字
            if (matches.Count > 0)
            {
                

               string num= ProcessMatches(matches).ToString();
                return num;
            }
            else
            {
                return 0.ToString();
            }

        }

        public static int ProcessMatches(MatchCollection matches)
        {
            bool hasZero = true;
            bool hasOneDigit = false;
            bool hasThreeDigit = false;
            bool hasFourDigit = false;
            int fourDigitValue = 0;
            int threeDigitValue = 0;

            foreach (Match match in matches)
            {
                if (int.TryParse(match.Value, out int num))
                {
                    if (num != 0)
                    {
                        hasZero = false;
                    }
                    if (num >= 1 && num <= 9)
                    {
                        hasOneDigit = true;
                    }
                    if (num >= 100 && num <= 999)
                    {
                        hasThreeDigit = true;
                        threeDigitValue = num; // 记录最后一个三位数

                    }
                    if (num >= 1000 && num <= 9999)
                    {
                        hasFourDigit = true;
                        fourDigitValue = num; // 记录最后一个四位数
                    }
                }
            }

            if (hasZero)
            {
                return 0; // 全部为 0
            }
            else if (hasFourDigit && hasOneDigit)
            {
                return fourDigitValue; // 同时存在四位数和一位数
            }
            else if (hasFourDigit && hasThreeDigit)// 同时存在四位数和三位数
            {
                return fourDigitValue;
            }
            else if (hasFourDigit)
            {
                return fourDigitValue; // 仅存在四位数
            }
            else if (hasFourDigit && hasThreeDigit)// 同时存在一位数和三位数
            {
                return threeDigitValue;
            }
            else if (hasThreeDigit)
            {
                return threeDigitValue;
            }

            else if (hasOneDigit)
            {
                return 0; // 仅存在一位数
            }
            else
            {
                return 0; // 默认返回
            }

            
        }
        //处理接收到的串口内容方法
        public static string GetUniqueConcatenatedString(string input)  //提取不同的字符串  并去掉其中\r\n
        {
            // 使用 HashSet 来存储唯一值
            HashSet<string> uniqueValues = new HashSet<string>();

            // 按照 \r\n 分割字符串
            string[] parts = input.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            // 将不同的部分添加到 HashSet 中
            foreach (var part in parts)
            {
                uniqueValues.Add(part);
            }

            // 拼接唯一的字符串
            return string.Join("", uniqueValues);
        }

        public static string GetUniqueConcatenatedString3(string input)
        {
            // 使用 HashSet 来存储唯一值
            HashSet<string> uniqueValues = new HashSet<string>();

            // 按照指定的分隔符分割字符串
            // 先分割按 \r\n
            string[] partsByNewLine = input.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var part in partsByNewLine)
            {
                // 检查是否以 *0 开头
                if (part.StartsWith("*0"))
                {
                    uniqueValues.Add(part);
                }
                else
                {
                    // 对于不以 *0 开头的部分，也可以添加（根据实际需求决定）
                    uniqueValues.Add(part);
                }
            }

            // 拼接唯一的字符串，您可以按需要选择分隔符，这里使用空字符串
            return string.Join("", uniqueValues);
        }


        public static string GetUniqueConcatenatedString2(string input)  //提取不同的字符串  并去掉其中\r\n
        {
            // 使用 HashSet 来存储唯一值
            HashSet<string> uniqueValues = new HashSet<string>();

            // 按照 \r\n 分割字符串
            string[] parts = input.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            // 将不同的部分添加到 HashSet 中
            foreach (var part in parts)
            {
                uniqueValues.Add(part);
            }

            // 拼接唯一的字符串
            return string.Join("-", uniqueValues);
        }
        public static string ExtractNumbers(string input)  //处理扫码读取到的字符串
        {
            // 使用正则表达式匹配纯数字部分
            Regex regex = new Regex(@"\d+");
            Match match = regex.Match(input);

            if (match.Success)
            {
                return match.Value;
            }

            return null; // 如果没有找到数字，则返回null
        }


        #endregion
        private string ATCommand(string ATCmd, string StCmd)
        {
            string text = "";
            if (!ATCmd.EndsWith("\u001a"))
            {
                if (!ATCmd.EndsWith("\r") && !ATCmd.EndsWith("\r\n"))
                {
                    ATCmd += "\r";
                }
            }
            serialPort1.WriteLine(ATCmd);
            if (serialPort1.BytesToRead > 0)
            {
                text = serialPort1.ReadExisting();
                if (text.IndexOf(ATCmd) > 0)
                {
                    text = text.Substring(text.IndexOf(ATCmd));
                }
                if (text == "" || text.IndexOf(StCmd) < 0)
                {
                    if (text != "")
                    {
                        if (text.Trim() == "ERROR")
                        {
                        }
                        if (text.IndexOf("+CMS ERROR") >= 0)
                        {
                            string[] array = new string[100];
                            array = text.Split(new char[]
                            {
                                ';'
                            });
                            if (array.Length > 1)
                            {
                                string text2 = array[1];
                            }
                        }
                    }
                }
            }
            for (int i = 0; i < 3; i++)
            {
                Thread.Sleep(1000);
                text += serialPort1.ReadExisting();
                if (text.IndexOf(StCmd) >= 0)
                {
                    break;
                }
            }
            return text;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            isClosing = true; // 设置标志以指示正在关闭
            ComClose = true;
            run = false;

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, args) =>
            {
                try
                {
                    if (serialPort2.IsOpen)
                    {
                        serialPort2.Close();
                        logNetYX.WriteInfo("程序关闭", "扫码串口关闭");
                    }

                    if (serialPort1.IsOpen)
                    {
                        serialPort1.Close();
                        logNetYX.WriteInfo("程序关闭", "称重串口关闭");
                    }
                }
                catch (Exception ex)
                {
                    logNetYX.WriteError("程序关闭", $"关闭串口时发生错误: {ex.Message}");
                }
            };

            worker.RunWorkerCompleted += (s, args) =>
            {
                logNetYX.WriteInfo("程序关闭", "退出程序");
            };

            worker.RunWorkerAsync();
            //Process.GetCurrentProcess().Kill();  //杀线程

        }
        m2_procedureprogres_volServer m2_Procedureprogres_VolServer = new m2_procedureprogres_volServer();
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length>0)
            {
                m2_procedureprogres_vol m2_Procedureprogres_Vol = new m2_procedureprogres_vol
                {
                    CodeBatch = textBox1.Text.Trim(),
                    DiameterAuto = 1,
                    Mode = 100,
                    WeightAuto = 100.00,
                    WidthClothAuto = 800.02
                };

                m2_Procedureprogres_VolServer.Update(m2_Procedureprogres_Vol);

            }
            else
            {
                MessageBox.Show("批号为空");
            }
               
        }


      

        private void notifyIcon2_DoubleClick(object sender, EventArgs e)
        {
            // 双击托盘图标时恢复窗体
            this.Show();
            this.WindowState = FormWindowState.Normal;
        }

        private void Form1_Resize(object sender, EventArgs e)
        {

            // 当窗体最小化时隐藏
            if (this.WindowState == FormWindowState.Minimized)
            {
                notifyIcon2.Visible = true; // 显示托盘图标
                this.Hide(); 
            }

        }

        private void button_writePen_Click(object sender, EventArgs e)
        {
            if ((txt1.Text.Trim().Length > 0) && (textBox_text.Text.Trim().Length > 0))
            {
                string text1 = txt1.Text.Trim();   //一号喷码信息
                string text = textBox_text.Text.Trim();   //二号喷码信息
                
                //读取数据库
                if (this.tcpclient != null)
                {
                    lbl_pm.Text = text1;
                    logNetYX.WriteInfo("喷码信息1记录：", text1);
                    logNetYX.WriteInfo("喷码信息2记录：", text);
                    //170g-2100-1622KG-AA"


                    logNetYX.WriteInfo("发送喷码信息：", "!!" + "v!1" + '"' + text1 + '"' + (char)13 + "!!" + "v!2" + '"' + text + '"' + (char)13 + "!!" + "v!1?" + (char)13 + "!!" + "v!2?" + (char)13);
                    TCPSendData("!!"+"v!1"+'"' + text1 + '"' + (char)13 + "!!" + "v!2" + '"' + text + '"' + (char)13+"!!"+"v!1?"+ (char)13 + "!!" + "v!2?" + (char)13);//喷码信息1和2
                    
                    
                    //TCPSendData("!!v!2\"" + text + "\"\r\n");//喷码信息2

                    if (siemensChanXian.Write("DB100.2.0", 86).IsSuccess)
                    {
                        logNetYX.WriteInfo("产线PLC", "手动写入DB100.2.0值为：86");

                    }
                }
            }
            else
            {
                MessageBox.Show("手动触发喷印信息未填写完全！");
                
            }
            
        }
    }
}
